<template>
  <div class="room-list-container">
    <el-card>
      <template #header>
        <div class="search-header">
          <h3>会议室查询</h3>
        </div>
      </template>
      
      <!-- 搜索表单 -->
      <el-form :model="searchForm" label-width="100px" inline>
        <el-form-item label="使用日期">
          <el-date-picker
            v-model="searchForm.date"
            type="date"
            placeholder="选择日期"
            :disabled-date="disabledDate"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="参会人数">
          <el-input-number v-model="searchForm.attendees" :min="1" :max="100" style="minWidth:100px;"/>
        </el-form-item>
        <el-form-item label="使用时间">
          <el-time-select
            v-model="searchForm.startTime"
            start="08:00"
            step="01:00"
            end="21:00"
            placeholder="开始时间"
            value-format="HH:mm"
          />
          <span class="mx-2">至</span>
          <el-time-select
            v-model="searchForm.endTime"
            start="08:00"
            step="01:00"
            end="21:00"
            placeholder="结束时间"
            :min-time="searchForm.startTime"
            value-format="HH:mm"
          />
        </el-form-item>

        <el-form-item label="会议室类型">
          <el-select v-model="searchForm.type" placeholder="请选择" style="minWidth:100px;">
            <el-option label="教室型" value="classroom" />
            <el-option label="圆桌型" value="round_table" />
          </el-select>
        </el-form-item>
        <el-form-item label="设备需求">
          <el-select
            v-model="searchForm.equipment"
            multiple
            collapse-tags
            collapse-tags-tooltip
            placeholder="可选择多个设备"
            clearable
            style="minWidth:100px;"
          >
            <el-option
              v-for="item in equipmentList"
              :key="item.equipmentId"
              :label="item.equipmentName"
              :value="item.equipmentId"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 会议室列表 -->
      <el-table :data="roomList" style="width: 100%" v-loading="loading">
        <el-table-column prop="name" label="会议室名称" />
        <el-table-column prop="type" label="类型">
          <template #default="{ row }">
            {{ row.type === 'classroom' ? '教室型' : '圆桌型' }}
          </template>
        </el-table-column>
        <el-table-column prop="maxCapacity" label="座位数" />

        <el-table-column prop="roomEquipments" label="设备支持">
            <template #default="{ row }">
                <template v-if="row.roomEquipments && row.roomEquipments.length">
                    <el-tag 
                      v-for="equipment in row.roomEquipments" 
                      :key="equipment.equipmentId"  
                      style="margin-right: 5px; margin-bottom: 5px"
                    >
                      {{ equipment.equipmentName }}
                    </el-tag>
                </template>
                <span v-else>-</span>
            </template>
        </el-table-column>
        <el-table-column prop="hourlyRentalPrice" label="每小时价格">
          <template #default="{ row }">
            ¥{{ row.hourlyRentalPrice }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleBook(row)">预订</el-button>
            <el-button size="small" @click="showDetail(row)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 会议室详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="会议室详情"
      width="500px"
    >
      <template v-if="selectedRoom">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="会议室名称">{{ selectedRoom.name }}</el-descriptions-item>
          <el-descriptions-item label="类型">{{ selectedRoom.type === 'classroom' ? '教室型' : '圆桌型' }}</el-descriptions-item>
          <el-descriptions-item label="座位数">{{ selectedRoom.maxCapacity }}</el-descriptions-item>
          <!-- <el-descriptions-item label="面积"> 100㎡</el-descriptions-item> -->
          <el-descriptions-item label="设备支持">
            <template v-if="selectedRoom.roomEquipments && selectedRoom.roomEquipments.length">
                <el-tag 
                  v-for="equipment in selectedRoom.roomEquipments" 
                  :key="equipment.equipmentId"  
                  style="margin-right: 5px; margin-bottom: 5px"
                >
                  {{ equipment.equipmentName }}
                </el-tag>
            </template>
            <span v-else>-</span> 
          </el-descriptions-item>
          <el-descriptions-item label="每小时价格">¥{{ selectedRoom.hourlyRentalPrice }}</el-descriptions-item>
        </el-descriptions>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import dayjs from 'dayjs'
import { ElMessage } from 'element-plus'
import 'element-plus/es/components/message/style/css'
import { getAvailableMeetingRooms } from '../../api/meetingRoomApi'
import { setSessionStorage } from '../../utils/common'

const router = useRouter()
const loading = ref(false)
const detailDialogVisible = ref(false)
const selectedRoom = ref(null)
const equipmentList = ref([
  {
    equipmentId: 1,
    equipmentName: '投影'
  },
  {
    equipmentId: 2,
    equipmentName: '音响'
  },

  {
    equipmentId: 3,
    equipmentName: '网络'
  }
])

const searchForm = ref({
  date: '',
  startTime: '',
  endTime: '',
  attendees: 1,
  type: '',
  equipment: []
})
const nowSearchForm = ref({
  date: '',
  startTime: '',
  endTime: '',
  personNum: 1,
  type: '',
  equipment: []
})

// 模拟会议室数据
const roomList = ref([])
const disabledDate = (time) => {
  return dayjs(time).isBefore(dayjs(), 'day') || 
         dayjs(time).isAfter(dayjs().add(60, 'day'), 'day')
}

async function handleSearch() {
  if(searchForm.value.date === '' || searchForm.value.startTime === '' || searchForm.value.endTime === ''||searchForm.value.attendees === 0||searchForm.value.type === '') {
    ElMessage.error('请先完成必填的查询条件')
    return
  }
  loading.value = true
  // TODO: 调用查询接口
  nowSearchForm.value = {
    date: searchForm.value.date,
    startTime: searchForm.value.startTime,
    endTime: searchForm.value.endTime,
    personNum: searchForm.value.attendees,
    type: searchForm.value.type,
    equipmentIds: searchForm.value.equipment.join(',') // 数组转逗号分隔字符串
  }
  try {
    const response = await getAvailableMeetingRooms(nowSearchForm.value)
    // 处理成功响应
    if (response.flag) {
      roomList.value = (response.result || []).filter(Boolean)
    }
  } catch (error) {
    console.error('请求失败:', error)
    if (error.response) {
      // 服务器返回了错误响应
      console.log('状态码:', error.response.status)
      console.log('错误数据:', error.response.data)
      // 显示错误信息给用户
      ElMessage.error(error.response.data.message || '请求失败')
    } else {
      // 其他错误（如网络错误）
      ElMessage.error('网络错误，请稍后重试')
    }
  }
  loading.value = false
}

const resetForm = () => {
  searchForm.value = {
    date: '',
    startTime: '',
    endTime: '',
    attendees: 1,
    type: '',
    equipment: []
  }
}

const  handleBook = (room) => {
  if (!nowSearchForm.value.date || !nowSearchForm.value.startTime || !nowSearchForm.value.endTime || !nowSearchForm.value.personNum || !nowSearchForm.value.type) {
    ElMessage.warning('请先选择使用日期,时间,参会人数,会议室类型')
    return
  }
  setSessionStorage("roomEquipments",room.roomEquipments)
  router.push({
    path: '/customer/createOrder',
    query: {
      roomId: room.roomId,
      date: nowSearchForm.value.date,
      name: room.name,
      type: room.type,
      maxCapacity: room.maxCapacity,
      hourlyRentalPrice: room.hourlyRentalPrice,
      startTime: nowSearchForm.value.startTime,
      endTime: nowSearchForm.value.endTime
    }
  })
}

const showDetail = (room) => {
  selectedRoom.value = room
  detailDialogVisible.value = true
}
</script>

<style scoped>
.room-list-container {
  padding: 20px;
}

.search-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.ml-1 {
  margin-left: 4px;
}

.mx-2 {
  margin: 0 8px;
}
</style> 